package com.pulse.base.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferMultipartFile implements MultipartFile {
    private final String name;
    private final String originalFilename;
    private final String contentType;
    private final byte[] content;

    public ByteBufferMultipartFile(String name, String originalFilename, String contentType, ByteBuffer byteBuffer) {
        this.name = name;
        this.originalFilename = originalFilename;
        this.contentType = contentType;

        // 将ByteBuffer转换为byte数组
        if (byteBuffer.hasArray()) {
            this.content = byteBuffer.array();
        } else {
            this.content = new byte[byteBuffer.remaining()];
            byteBuffer.get(this.content);
        }
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return this.content.length == 0;
    }

    @Override
    public long getSize() {
        return this.content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return this.content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

    @Override
    public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
        try (InputStream inputStream = getInputStream()) {
            java.nio.file.Files.copy(inputStream, dest.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        }
    }
}


class Main {
    public static void main(String[] args) {
        // 示例数据
        String content = "Hello, this is a test file content";
        ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());

        // 创建MultipartFile
        MultipartFile multipartFile = new ByteBufferMultipartFile(
                "fileFieldName",        // 表单字段名
                "test.txt",             // 原始文件名
                "text/plain",           // 内容类型
                byteBuffer             // ByteBuffer数据
        );

        // 现在可以使用multipartFile了
        System.out.println("File size: " + multipartFile.getSize());
    }
}